package model.commands.misc;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import model.Environment;
import model.Interpreter;
import model.SyntaxErrorException;
import model.commands.Command;

/**
 * Name:
 * LOAD filename
 * 
 * Description:
 * Loads and executes the commands written in filename
 *
 * @author Erick Gonzalez
 */
public class LoadCommand extends Command {
    private static final String COMMAND_LIBRARY_PATH = "CommandLibrary/";
    private Interpreter myInterpreter;
    private String myFileName;

    /**
     * 
     * @param interpreter an interpreter
     * @param fileName a fileName
     */
    public LoadCommand (Interpreter interpreter, String fileName) {
        myInterpreter = interpreter;
        myFileName = fileName;
    }

    @Override
    public int evaluate (Environment e) throws SyntaxErrorException {
        try {
            List<String> loadedCommands = new ArrayList<String>();
            Scanner s = new Scanner(new File(COMMAND_LIBRARY_PATH + myFileName));
            while (s.hasNextLine()) {
                loadedCommands.add(s.nextLine());
            }
            int returnValue = 0;
            for (String commandString : loadedCommands) {
                returnValue = myInterpreter.interpretAndExecute(new Scanner(commandString));
            }
            return returnValue;
        }
        catch (FileNotFoundException e1) {
            return 0;
        }
    }

}
